<?php 
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\System as SystemModel;

/**
 *		微信支付控制器
 */

class Wxpay extends AdminBase {
    private $vendorPath = '';
    protected $system_model;

	// 初始化参数
	public function _initialize() {

	// 	$this->system_model = new SystemModel();



	// 	$res = $this->system_model->where(array('code'=>'wxpay'))->column('config');

	// 	$res = json_decode($res[0], true);
	// // halt($res);


	// 	\WxPayConfig::setAppId($res['appid']);
	// 	\WxPayConfig::setAppSecret($res['appsecret']);
	// 	\WxPayConfig::setKey($res['mchkey']);
	// 	\WxPayConfig::setMchId($res['mchid']);
	}
	
	public function test(){
		echo input('echostr');

		//接收xml数据
//接收xml数据
		$postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
//把xml数据转化成对象
		$postObj = simplexml_load_string($postStr);


		$fromuserName = $postObj->FromUserName;
		$touserName = $postObj->ToUserName;
		$time = time();
		$msgType = $postObj->MsgType;
		$keywords = $postObj->Content;
		$textTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[%s]]></MsgType>
		<Content><![CDATA[%s]]></Content>
	</xml>";

	$musicTpl = "<xml>
	<ToUserName><![CDATA[%s]]></ToUserName>
	<FromUserName><![CDATA[%s]]></FromUserName>
	<CreateTime>%s</CreateTime>
	<MsgType><![CDATA[%s]]></MsgType>
	<Music>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<MusicUrl><![CDATA[%s]]></MusicUrl>
		<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
	</Music>
</xml>";
$newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
	<item>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<PicUrl><![CDATA[%s]]></PicUrl>
		<Url><![CDATA[%s]]></Url>
	</item>
</Articles>
</xml>";

//关注事件回复
if($postObj->MsgType == 'event'){
	if($postObj->Event == 'subscribe'){
		$msgType = 'news';
		$title = '三月三!!!!';
		$des = '好日子,欢迎你的到来!!!!';
		$picurl = 'http://boolceshi.ittun.com/xie.jpg';
		$url = 'http://www.zixue.it';
		$resultful = sprintf($newsTpl,$fromuserName,$touserName,$time,$msgType,$title,$des,$picurl,$url);
		echo $resultful;
	}elseif($postObj->Event == 'CLICK'){
		if($postObj->EventKey == '音乐'){
			$msgType = 'music';
			$title = '许嵩';
			$des = '好听,唯美';
			$url = 'http://boolceshi.ittun.com/22.mp3';
			$resultful = sprintf($musicTpl,$fromuserName,$touserName,$time,$msgType,$title,$des,$url,$url);
			echo $resultful;
		}
	}
}			

//关键词自动回复
if($postObj->MsgType == "text" ){
	if($postObj->Content == '1'){
		$content = '你好!!!!';
		$resultful = sprintf($textTpl,$fromuserName,$touserName,$time,$msgType,$content);
		echo $resultful;
	}elseif($postObj->Content == '你好'){
		$content = '欢迎你来到布尔教育!!!';
		$resultful = sprintf($textTpl,$fromuserName,$touserName,$time,$msgType,$content);
		echo $resultful;
	}elseif($keywords == '音乐'){
		$msgType = 'music';
		$title = '许嵩';
		$des = '好听,唯美';
		$url = 'http://boolceshi.ittun.com/22.mp3';
		$resultful = sprintf($musicTpl,$fromuserName,$touserName,$time,$msgType,$title,$des,$url,$url);
		echo $resultful;
	}elseif($keywords == '图文'){
		$msgType = 'news';
		$title = '微信公开课!!!';
		$des = '好听,好学,好玩!!!';
		$picurl = 'http://boolceshi.ittun.com/bool.jpg';
		$url = 'http://www.baidu.com';
		$resultful = sprintf($newsTpl,$fromuserName,$touserName,$time,$msgType,$title,$des,$picurl,$url);
		echo $resultful;
	}else{
		$content = '你好你好你好!!!!';
		$resultful = sprintf($textTpl,$fromuserName,$touserName,$time,$msgType,$content);
		echo $resultful;
	}
}elseif($postObj->MsgType == 'image'){
	$url = 'https://api-cn.faceplusplus.com/facepp/v3/detect';
	$data = [
	'api_key'=>'AWHXLEMVlhTju6raJrlAJS5R4gPe8jX_',
	'api_secret'=>'j3etjvp-DZsz_SJpXdZNN0IOovVgO1KK',
	'image_url'=>$postObj->PicUrl,
	'return_landmark'=>'1',
	'return_attributes'=>'age,gender',
	];

	$curl = curl_init();
		//设置参数
	curl_setopt($curl,CURLOPT_URL,$url);
	curl_setopt($curl, CURLOPT_HEADER,0);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		//发送请求信息
	$da = curl_exec($curl);
		//关闭请求资源
	curl_close($curl);
	$arr = json_decode($da,true);
	$num = count($arr['faces']);
	$age = $arr['faces']['attributes']['age']['value'];
	if($num == '0'){

		$content = '你的图片真好看!!!';
	}else{
		$content = $num.'个人:'.$age;
	}
	$msgType = 'text';
	$resultful = sprintf($textTpl,$fromuserName,$touserName,$time,$msgType,$content);
	echo $resultful;
}elseif($postObj->MsgType == 'voice'){
	$msgType = 'text';
	$content = '你的声音真好听!!!';
	$resultful = sprintf($textTpl,$fromuserName,$touserName,$time,$msgType,$content);
	echo $resultful;
}elseif($postObj->MsgType == 'location'){
	$msgType = 'text';
	$location_x = $postObj->Location_X;
	$location_y = $postObj->Location_Y;
	$url = 'http://api.map.baidu.com/place/v2/search?query=%E5%8E%95%E6%89%80&location=' . $location_x .','. $location_y .'&scope=2&radius=2000&output=json&ak=88H9M1sNCCGGWVz7A3VZjq6xCSLx6Va5';
	$json = file_get_contents($url);
	$arr = json_decode($json,true);
	$content = '';
	foreach($arr['results'] as $k => $v){
		$content .= $v['name'] . '在' . $v['address'] . ',' . '距离你有' . $v['detail_info']['distance'] ."米,\n";
	}
	$resultful = sprintf($textTpl,$fromuserName,$touserName,$time,$msgType,$content);
	echo $resultful;
}	



}

	/**
	 *  @desc 支付二维码
	 */
	// public function getQrcode($data){
		
 //    	$out_trade_no = $data['out_trade_no'];
		
 //    	$notify = new \NativePay();
    	
 //    	$input = new \WxPayUnifiedOrder();
 //    	$input->SetBody('终端续费 - ' . $data['payment_name']);
 //    	$input->SetOut_trade_no($out_trade_no);
 //    	$input->SetTotal_fee($data['payment_fee'] * 100);
 //    	$input->SetTime_start(date("YmdHis"));
 //    	$input->SetTime_expire(date("YmdHis", time() + 600));
 //    	$notify_url = U('/Main/Wxpay/notify', '', true, true);
 //    	if (isSsl()) {
 //    		$notify_url = str_replace('http://', 'https://', $notify_url);
 //    	}
 //    	$input->SetNotify_url($notify_url);
 //    	$input->SetTrade_type("NATIVE");
 //    	$input->SetProduct_id($out_trade_no);
 //    	$result = $notify->GetPayUrl($input);
 //    	$url = $result["code_url"];
 //    	$url = (isSsl() ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].'/Application/Common/Library/Vendor/Wxpay/example/qrcode.php?data='.$url;
 //    	return $url;
 //    }
    
 //    //异步通知
 //    public function notify() {

	// 	$WxPayNotify = new \WxPayNotify();
		
	// 	//初始化日志
	// 	$logPath = SITE_PATH . '/Uploads/pay/wx_'.date('Y-m-d').'.log';
	// 	$logHandler= new \CLogFileHandler($logPath);
	// 	$log = \Log::Init($logHandler, 15);
    	
	// 	\Log::DEBUG("begin notify");
		
	// 	//获取通知的数据
	// 	$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	// 	//如果返回成功则验证签名
	// 	try {
	// 		$data = \WxPayResults::Init($xml);
	// 	} catch (\WxPayException $e){
	// 		$msg = $e->errorMessage();
	// 		\Log::DEBUG($msg);
			
	// 		$WxPayNotify->SetReturn_code("FAIL");
	// 		$WxPayNotify->SetReturn_msg($msg);
	// 		$WxPayNotify->ReplyNotify(false);
	// 		return;
	// 	}
	
	// 	if(!array_key_exists("transaction_id", $data)){
	// 		$msg = "输入参数不正确";
	// 		$WxPayNotify->SetReturn_code("FAIL");
	// 		$WxPayNotify->SetReturn_msg($msg);
	// 		$WxPayNotify->ReplyNotify(false);
	// 		return;
	// 	}
	// 	//查询订单，判断订单真实性
	// 	if(!$this->Queryorder($data["transaction_id"])){
	// 		$msg = "订单查询失败";
	// 		$WxPayNotify->SetReturn_code("FAIL");
	// 		$WxPayNotify->SetReturn_msg($msg);
	// 		$WxPayNotify->ReplyNotify(false);
	// 		return;
	// 	}

	// 	$out_trade_no = $data['out_trade_no'];
	// 	// 判断缴费记录是否已更新
	// 	$PayHistoryModel = D('PayHistory');
	// 	$where = array('out_trade_no' => $out_trade_no, 'status' => 1);
	// 	$res = $PayHistoryModel->where($where)->count();
	// 	if ($res) {
	// 		//该分支在成功回调到NotifyCallBack方法，处理完成之后流程
	// 		$WxPayNotify->SetReturn_code("SUCCESS");
	// 		$WxPayNotify->SetReturn_msg("OK");
	// 		$WxPayNotify->ReplyNotify(false);
	// 		return;
	// 	}
		
	// 	$upData = array(
	// 		'out_trade_no'		=> $out_trade_no,
	// 		'time'				=> strtotime($data['time_end']),
	// 		'total_fee'			=> $data['total_fee'] / 100,
	// 		'third_trade_no'	=> $data['transaction_id']
	// 	);
	// 	$goPayController = A('GoPay');
	// 	$goPayController->updateAfterPay($upData);
	// 	\Log::DEBUG('wxpay success');
		
	// 	//该分支在成功回调到NotifyCallBack方法，处理完成之后流程
	// 	$WxPayNotify->SetReturn_code("SUCCESS");
	// 	$WxPayNotify->SetReturn_msg("OK");
	// 	$WxPayNotify->ReplyNotify(false);
 //    }
    
 //    private function Queryorder($transaction_id) {
		
 //    	$input = new \WxPayOrderQuery();
 //    	$input->SetTransaction_id($transaction_id);
 //    	$result = \WxPayApi::orderQuery($input);
 //    	\Log::DEBUG("query:" . json_encode($result));
 //    	if(array_key_exists("return_code", $result)
 //    			&& array_key_exists("result_code", $result)
 //    			&& $result["return_code"] == "SUCCESS"
 //    			&& $result["result_code"] == "SUCCESS")
 //    	{
 //    		return true;
 //    	}
 //    	return false;
 //    }
	
	// /**
	//  * @desc 终端支付之后，腾讯的异步通知
	//  */
	// public function devicePayNotify() {
	// 	$get  = json_encode($_GET);
	// 	$post = json_encode($_POST);
		
	// 	$log_path = './Uploads/tmp/';
	// 	if (!file_exists($log_path)) {
	// 		mkdir($log_path, 0755, true);
	// 	}
	// 	$log_file = $log_path.'wxpay_notify.log';
		
	// 	$log = "[".date('Y-m-d H:i:s')."]\r\nGET: {$get}\r\nPOST: {$post}\r\n\r\n";
	// 	file_put_contents($log_file, $log, FILE_APPEND);
		
	// 	return true;
	// }
	
	// /**
	//  * 获取订单的二维码地址
	//  * @param array $orderData	订单数据
	//  * @return string $url
	//  */
	// public function getOrderQrCode($orderData){
	// 	$out_trade_no = $orderData['out_trade_no'];
		
 //    	$notify = new \NativePay();
    	
 //    	$input = new \WxPayUnifiedOrder();
 //    	$input->SetBody('生意火平台支付');
 //    	$input->SetOut_trade_no($out_trade_no);
 //    	$input->SetTotal_fee($orderData['amount'] * 100);
 //    	$input->SetTime_start(date("YmdHis"));
 //    	$input->SetTime_expire(date("YmdHis", time() + 600));
 //    	$notify_url = U('/Main/Wxpay/notify', '', true, true);
 //    	if (isSsl()) {
 //    		$notify_url = str_replace('http://', 'https://', $notify_url);
 //    	}
 //    	$input->SetNotify_url($notify_url);
 //    	$input->SetTrade_type("NATIVE");
 //    	$input->SetProduct_id($out_trade_no);
 //    	$result = $notify->GetPayUrl($input);
 //    	$url = $result["code_url"];
 //    	$url = (isSsl() ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].'/Application/Common/Library/Vendor/Wxpay/example/qrcode.php?data='.$url;
 //    	return $url;
	// }
}